import { i18n } from '@/plugins/vueI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { setHtmlPageLang } from '@/plugins/vueI18n/helper'

const setI18nLanguage = (locale: LocaleType) => {
  const localeStore = useLocaleStoreWithOut()

  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale
  } else {
    ;(i18n.global.locale as any).value = locale
  }
  localeStore.setCurrentLocale({
    lang: locale
  })
  setHtmlPageLang(locale)
}

export const useLocale = () => {
  // Switching the language will change the locale of useI18n
  // And submit to configuration modification
  const changeLocale = async (locale: LocaleType) => {
    const globalI18n = i18n.global

    // 直接导入所有语言文件
    const zhCN = await import('../../locales/zh-CN')
    const en = await import('../../locales/en')

    // 设置对应的语言消息
    if (locale === 'zh-CN' || locale === 'zh') {
      globalI18n.setLocaleMessage(locale, zhCN.default)
    } else if (locale === 'en') {
      globalI18n.setLocaleMessage(locale, en.default)
    }

    setI18nLanguage(locale)
  }

  return {
    changeLocale
  }
}
